/**    
 * @Description:博客园地址：https://www.cnblogs.com/zumengjie/      
 * @author:顶风少年   
 * @date:   2021年4月1日 下午10:55:40
 */
package datang.dtdb.session.defaults;

import java.util.ArrayList;
import java.util.List;

import datang.dtdb.exceptions.SqlSessionException;
import datang.dtdb.exceptions.TooManyResultsException;
import datang.dtdb.executor.Executor;
import datang.dtdb.mapping.MappedStatement;
import datang.dtdb.session.Configuration;
import datang.dtdb.session.SqlSession;

/**
 * 默认的SqlSession实现CRUD功能
 */
public class DefaultSqlSession implements SqlSession {

	private Configuration configuration;

	private Executor executor;

	public DefaultSqlSession(Configuration configuration, Executor executor, boolean autoCommit) {
		this.configuration = configuration;
		this.executor = executor;
	}

	/**
	 * 查询结果返回单行记录，无入参
	 */
	@Override
	public <E> E selectOne(String statetment) {
		return selectOne(statetment, null);
	}

	/**
	 * 查询结果返回单行记录，有入参
	 */
	@Override
	public <E> E selectOne(String statetment, Object paramenter) {
		List<E> list = selectList(statetment, paramenter);
		if (list.size() == 1) {
			return list.get(0);
		} else {
			throw new TooManyResultsException("期望返回1个结果，实际返回" + list.size() + "个结果");
		}
	}

	/**
	 * 查询接口返回List集合，无入参
	 */
	@Override
	public <E> List<E> selectList(String statement) {
		return selectList(statement, null);
	}

	/**
	 * 查询接口返回List集合，有入参
	 */
	public <E> List<E> selectList(String statement, Object paramenter) {
		MappedStatement mappedStatement = configuration.getMappedStatement(statement);
		if (mappedStatement == null) {
			throw new SqlSessionException("未查询到statement" + statement);
		}
		return executor.query(mappedStatement, paramenter, null, null);
	}

	/**
	 * 删除接口返回执行条数，无入参
	 */
	@Override
	public int delete(String statement) {
		return delete(statement, null);
	}

	/**
	 * 删除接口返回执行条数，有入参
	 */
	@Override
	public int delete(String statement, Object paramenter) {
		return update(statement, paramenter);
	}

	/**
	 * 新增接口返回执行条数，无入参
	 */
	@Override
	public int insert(String statement) {
		return insert(statement, null);
	}

	/**
	 * 新增接口返回执行条数，有入参
	 */
	@Override
	public int insert(String statement, Object paramenter) {
		return update(statement, paramenter);
	}

	/**
	 * 修改接口返回执行条数，无入参
	 */
	@Override
	public int update(String statement) {
		return update(statement, null);
	}

	/**
	 * 修改接口返回执行条数，有入参
	 */
	@Override
	public int update(String statement, Object paramenter) {
		MappedStatement mappedStatement = configuration.getMappedStatement(statement);
		if (mappedStatement == null) {
			throw new SqlSessionException("未查询到statement" + statement);
		}
		return executor.update(mappedStatement, paramenter);
	}

	/**
	 * 提交事务
	 */
	@Override
	public void close() {
		executor.close();
	}

	/**
	 * 回滚事务
	 */
	@Override
	public void rollback() {
		executor.rollback();
	}

	/**
	 * 提交事务
	 */
	@Override
	public void commit() {
		executor.commit();
	}

}
